<template>
  <div class="container">
    <FortenVxetableStatic ref="fortenStatic" :data="tableData" :columns="tableColumns" :maxHeight="maxHeight" :btnList="btnList" @userFun="userFun" pkName="name"
    :searchFieldArr="['name','title']"
    :disabled="disabled"
    searchPlaceholder="搜索字段名/显示名"
    ></FortenVxetableStatic>

    <!--设置验证规则窗口-->
    <el-dialog :title="'编辑验证规则，字段：'+rowSelected.title" :visible.sync="ruleWindowVisible" :append-to-body="true" width="70%">
      <div class="tag-container">

      </div>
      <div class="rule-container">
        <el-row>
          <el-col :span="6">
            <el-card style="height:500px;margin-right:10px">
              <h3 v-show="getRuleStock.length < 1">已全部添加</h3>
              <ul>
                <li v-for="item in getRuleStock" :key="item.key">
                  <el-form inline>
                    <el-form-item>
                      <div v-text="item.label" style="width:100px"></div>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="success" size="mini" @click="handleAddRule(item)">加入</el-button>
                    </el-form-item>
                  </el-form>
                </li>
              </ul>
            </el-card>
          </el-col>
          <el-col :span="18">
            <el-card style="height:500px;margin-right:10px">
              <ul>
                <el-form inline>
                  <el-form-item>
                    <div style="width:100px">-</div>
                  </el-form-item>
                  <el-form-item>
                    <div style="width:200px;text-align:center;font-weight:bold;font-size:14px">出错提示</div>
                  </el-form-item>
                  <el-form-item>
                    <div style="width:400px;text-align:center">规则设定(正则表达式，不带前后/)</div>
                  </el-form-item>
                </el-form>
                <h3 v-show="!rowSelected.rule || rowSelected.rule.length < 1">未添加任何验证规则</h3>
                <li v-for="(item, index) in rowSelected.rule" :key="item.key">
                  <el-form inline>
                    <el-form-item>
                      <div v-text="item.label" style="width:100px"></div>
                    </el-form-item>
                    <el-form-item>
                      <el-input v-model="item.content ? item.content.message : item.message" placeholder="出错提示" style="width:200px;"/>
                    </el-form-item>
                    <el-form-item>
                      <el-input v-if="(item.key === 'custom' || (item.content && item.content.pattern))" v-model="item.content.pattern"
                                style="width:400px" />
                      <el-input v-else style="width:400px" :disabled="true" value="不能修改" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="danger" size="mini" @click="handleRemoveRule(item, index)">移除</el-button>
                    </el-form-item>
                  </el-form>
                </li>
              </ul>
              <!-- <div>{{ JSON.stringify(this.baseColumns) }}</div> -->
            </el-card>
          </el-col>
        </el-row>

      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable*/
import FortenVxetableStatic from '@/components/common/FortenVxetableStatic.vue'
let dictMap = {
  dictTypeList: [],
  inputTypeSource: [
    { value: 'none', label: '不显示' },
    { value: 'disabled', label: '禁止用户输入' },
    { value: 'text', label: '文本框' },
    { value: 'textarea', label: '文本域' },
    { value: 'number', label: '数值框' },
    { value: 'date', label: '日期' },
    { value: 'select', label: '下拉框' },
    { value: 'checkbox', label: '复选框' },
    { value: 'switch', label: '开关' },
    { value: 'dataview', label: '数据视图' },
    { value: 'element', label: 'elementUI' },
  ]
}


export default {
  title:'数据视图维护输入列',
  props:['data', 'disabled'],
  components: {
    FortenVxetableStatic
  },
  mounted() {
    this.init()
  },
  computed: {
    //规则列表
    getRuleStock() {
      if (!this.rowSelected || !this.rowSelected.rule || this.rowSelected.rule.length < 1) return this.ruleStock
      return this.ruleStock.filter(item => {
        return !this.rowSelected.rule.find(val => val.key === item.key)
      })
    },
  },
  data() {
    return {
      tableData: [],
      //字段列表
      tableColumns: [],
      //按钮列表
      btnList: [{
        key: 'delete',
        icon: 'el-icon-delete',
        size: 'mini',
        style: {padding: '6px'},
        type: 'danger',
        title: '移除该列'
      }],
      maxHeight: window.innerHeight - 380,
      //验证规则窗口显示
      ruleWindowVisible: false,

      //验证规则列表
      ruleStock: [
        { key: 'require', label: '必填', for: '#', content: { required: true, message: '必填项', trigger: 'blur' } },
        { key: 'date', label: '日期型', for: '#date#,#datetime#', content: { required: false, type: 'date', message: '请输入日期型的内容', trigger: 'blur' } },
        { key: 'number', label: '数值型', for: '#int#,#bigint#,#smallint#,#tinyint#', content: { required: false, type: 'number', message: '请输入数字', trigger: 'blur' } },
        { key: 'mobile', label: '手机', for: '#varchar#', content: { required: false,  pattern: '/^1[345789]\\d{9}$/ig', message: '手机号格式错误', trigger: 'blur' } },
        { key: 'custom', label: '自定义', for: '#', content: { required: false, pattern: '', message: '在此输入出错提示', trigger: 'blur' } }
      ],
      //所选行
      rowSelected: {
      },
      //所选列
      columnSelected: {},
    }
  },
  watch: {
    data(newVal) {
      //修改，增加默认值
      this.tableData = newVal
      this.tableColumns.filter(column => this.strings.isNotBlank(column.default)).forEach(column => {
        for(let i = 0; i < this.tableData.length; i++ ) {
          if (!this.tableData[i][column.field]) {
            this.tableData[i][column.field] = column.default
          }
        }
      })
    },
  },
  methods: {
    //初始化操作
    init() {
      //数据字典
      dictMap.dictTypeList = this.$store.state.dicts.dictTypeList.map(ob => {
        return {value: ob.code, label: ob.name}
      })

      //列配置
      this.tableColumns = [
        {field: 'name', title: '字段名', minWidth: 120, fixed: 'left', titleHelp: '数据字段名称'},
        {
          field: 'title',
          title: '显示名',
          minWidth: 120,
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          fixed: 'left'
        },
        {field: 'dataType', title: '数据类型', minWidth: 100, titleHelp: '数据库字段类型'},

        {
          field: 'isNullable',
          title: '可空',
          minWidth: 80,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '是否可以为空',
          filter: true

        },

        {
          field: 'formsort',
          title: '显示顺序',
          minWidth: 100,
          editRender: {name: 'ElInputNumber', attrs: {min: 0, max: 999}},
          titleHelp: '在表单界面的显示顺序'
        },

        {
          field: 'inputType',
          title: '输入类型',
          minWidth: 140,
          editRender: {
            name: 'ElSelect',
            options: dictMap.inputTypeSource,
            props: {placeholder: `请选择`, filterable: true, clearable: true}
          },
          titleHelp: '用户输入使用什么控件',
          filter: true

        },
        {
          field: 'dict',
          title: '字典类型',
          minWidth: 140,
          editRender: {
            name: 'ElSelect',
            options: dictMap.dictTypeList,
            props: {placeholder: `请选择`, filterable: true, clearable: true}
          },
          titleHelp: '下拉框等类型时需要指定数据字典',
          filter: true
        },

        {
          field: 'colSpan',
          title: '列数',
          minWidth: 80,
          editRender: {name: 'ElInputNumber', attrs: {min: 0, max: 24}},
          titleHelp: '栅格列数：1-24',
          default: 12
        },

        {
          field: 'isNewRow',
          title: '新行',
          minWidth: 80,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '是新行的话，将换行显示'
        },

        {
          field: 'rule',
          title: '验证',
          minWidth: 200,
          titleHelp: '保存时数据校验类型',
          formatter: ({row, column}) => {
            if (!row.rule || row.rule.length == 0) return ''
            let  title = []
            row.rule.forEach(rule => {
              if (rule.label) {
                title.push(rule.label)
              } else {
                title.push(rule.message)
              }
            })

            return title.join(',')
          },
          slots: {
            default(scope) {
              let config = []
              let rules = scope.row.rule
              if (rules) {
                let  html = ['<div style="max-width: 150px;overflow: auto;">']
                rules.forEach(rule => {
                  if (rule.required) {
                    html.push(`<el-tag  style="background-color: #f56c6c;border-color: #f56c6c;color: #fff;font-size: 12px;margin-right: 5px">必填</el-tag>`)
                  }else {
                    html.push(`<el-tag  style="background-color: #e6a23c;border-color: #e6a23c;color: #fff;font-size: 12px;margin-right: 5px">${rule.label}</el-tag>`)
                  }
                })
                html.push('</div>')
                config.push( {
                  showType: 'html',
                  value: html.join('')
                })
              }

              config.push(
                {
                  showType: 'button',
                  key: 'rule',
                  icon: 'el-icon-edit',
                  size: 'mini',
                  style: {
                    padding: '3px',
                    position: 'absolute',
                    right: '7px',
                    top: '14px'
                  },
                  status: 'primary',
                  title: '设置验证规则'
                }
              )

              return config
            }
          }
        },

        {
          field: 'flagTabMain',
          title: '主控件',
          minWidth: 80,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '可视化设计使用，主控件的话，将显示该控件标题'
        },

        {
          field: 'tabPaneIndex',
          title: '面板索引',
          minWidth: 80,
          editRender: {name: 'ElInputNumber', attrs: {min: 0, max: 999}},
          titleHelp: '可视化设计使用，一个tab标签内有多个面板时，排序顺序'
        },

        {
          field: 'userMsg',
          title: '用户提示信息',
          minWidth: 100,
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          titleHelp: '可视化设计使用，用户提示信息'
        },
        {
          field: 'source',
          title: '数据源(即将废弃)',
          minWidth: 200,
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          titleHelp: '初始化下拉框控件的后台地址，比如：/base/dept/listByUserId'
        }
      ]
    },

    //回调函数
    userFun({config, scope}) {
      this.rowSelected = scope.row
      this.columnSelected = scope.row.column
      switch (config.key) {
        case 'rule': //设置验证规则
          this.handleRuleWindowOpen(scope)
          break

      }
    },

    //打开验证规则窗口
    handleRuleWindowOpen(scope) {
      this.ruleWindowVisible = true
    },
    //添加规则
    handleAddRule(item) {
      let cp = JSON.parse(JSON.stringify(item))
      if (!this.rowSelected.rule) {
        this.rowSelected.rule = []
      }
      this.rowSelected.rule.push(cp)
      this.$refs.fortenStatic.changeDataFilter()
      this.$forceUpdate()
    },
    //移除规则
    handleRemoveRule(item, index) {
      this.rowSelected.rule.splice(index, 1)
      this.$forceUpdate()
    },
  }
}
</script>

<style lang="scss" scoped>
  .container{
    height: auto !important;
  }
</style>
